package com.bdqn.controller;
import com.bdqn.config.MyShiroRealm;
import com.bdqn.pojo.Right;
import com.bdqn.pojo.Role;
import com.bdqn.pojo.User;
import com.bdqn.service.PasswordService;
import com.bdqn.service.RoleService;
import com.bdqn.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
public class IndexController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //从redis中数据的key
    private  String SHIRO_LOGIN_COUNT = "shiro_login_count";
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private PasswordService passwordService;

    @RequestMapping(value = "/403")
    public String unauthorized(){
        return "403";
    }
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/main")
    public String toMain(){
        return "main";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginUser");
        session.invalidate();
        SecurityUtils.getSubject().logout(); // Shiro注销
        return "redirect:/login";
    }

    @PostMapping("/login")
    public String doLogin(String usrName, String usrPassword,Model model,HttpSession session){
        try {
            usrPassword=passwordService.encryptPassword(usrPassword);
            UsernamePasswordToken token=new UsernamePasswordToken(usrName,usrPassword);
            Subject subject= SecurityUtils.getSubject();
            subject.login(token);
            //认证登录，清空登录计数
            stringRedisTemplate.delete(SHIRO_LOGIN_COUNT+usrName);
            // 认证(登录)成功
            User user=(User) subject.getPrincipal();
            Role role=user.getRole();//如果一对多关联不是马上加载，则需要通过用户获取角色
            List<Right> rights=roleService.findRightsByRole(role);
            role.getRights().addAll(rights);
            session.setAttribute("loginUser",user);
            //清空权限缓存
            RealmSecurityManager rsm= (RealmSecurityManager) SecurityUtils.getSecurityManager();
            MyShiroRealm realm= (MyShiroRealm) rsm.getRealms().iterator().next();
            realm.clearMyCachedAuthorizationInfo();
            return "redirect:/main";
        }catch (UnknownAccountException | IncorrectCredentialsException e){
            model.addAttribute("message","用户名或密码错误，登录失败！");
            return "login";
        }catch (LockedAccountException e){
            model.addAttribute("message","用户被禁用，登录失败！");
            return "login";
        }catch (AuthenticationException e){
            model.addAttribute("message","认证异常，登录失败！");
            return "login";
        }
    }
}
//        User user=userService.login(usrName, usrPassword);
//        if (user!=null){
//            request.getSession().setAttribute("loginUser", user);
//            return "redirect:/main";
//        }else{
//            request.setAttribute("message","登录失败，用户名或密码错误！");
//            return "/login";
//        }
